<?php

namespace app\store\controller;

use app\store\model\Goods as GoodsModel;
use app\store\model\Category as CategoryModel;
use app\store\service\Goods as GoodsService;
use think\db;

/**
 * 商品管理控制器
 * Class Goods
 * @package app\store\controller
 */
class Goods extends Controller
{
    /**
     * 商品列表(出售中)
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function index()
    {
        // 获取全部商品列表
        $model = new GoodsModel;
        $list = $model->getList(array_merge(['status' => -1], $this->request->param()));
        // 商品分类
        $catgory = CategoryModel::getCacheTree();
        return $this->fetch('index', compact('list', 'catgory'));
    }

    /**
     * 添加商品
     * @return array|mixed
     * @throws \think\exception\PDOException
     */
    public function add()
    {
        if (!$this->request->isAjax()) {
            $levellist = Db::name('server_level')->select()->toArray();
            return $this->fetch(
                'add',
                array_merge(GoodsService::getEditData(null, 'add'),compact('levellist'))
            );
        }
        $model = new GoodsModel;
        $data = $this->postData('goods');
        if($_FILES){
            $upfile = $_FILES['goods_video']?$_FILES['goods_video']:"";
            if($upfile){
                $res = $this->upload_file($upfile);
                $data['goods_video'] = $res;
            }
        }
        $level_ids = $_POST['level_id'];
        $level_commission = $_POST['level_commission'];

        $level_set = array();
        foreach($level_ids as $k=>$v){
            $level_set[$k]['id'] = $v;
            $level_set[$k]['commission'] = $level_commission[$k];
        }

        $level_set_str = json_encode($level_set);

        $data['level_set'] = $level_set_str;

        if ($model->add($data)) {
            return $this->renderSuccess('添加成功', url('goods/index'));
        }
        return $this->renderError($model->getError() ? $model->getError() : '添加失败');
    }

    /**
     * 一键复制
     * @param $goods_id
     * @return array|mixed
     * @throws \think\exception\PDOException
     */
    public function copy($goods_id)
    {
        // 商品详情
        $model = GoodsModel::detail($goods_id);
        if (!$this->request->isAjax()) {
            return $this->fetch(
                'edit',
                array_merge(GoodsService::getEditData($model, 'copy'), compact('model'))
            );
        }
        $model = new GoodsModel;
        if ($model->add($this->postData('goods'))) {
            return $this->renderSuccess('添加成功', url('goods/index'));
        }
        return $this->renderError($model->getError() ?: '添加失败');
    }

    /**
     * 商品编辑
     * @param $goods_id
     * @return array|bool|mixed
     */
    public function edit($goods_id)
    {
        // 商品详情
        $model = GoodsModel::detail($goods_id);
        if (!$this->request->isAjax()) {
            $levellist = Db::name('server_level')->select()->toArray();
            $levelset = json_decode($model['level_set'],true);

            foreach($levellist as $k=>$v){
                $levellist[$k]['commission'] = $levelset[$k]['commission'];
            }
            log_print(GoodsService::getEditData($model), compact('model'));
            return $this->fetch(
                'edit',
                array_merge(GoodsService::getEditData($model), compact('model','levellist'))
            );
        }
        $data = $this->postData('goods');

        if($_FILES){
            $upfile = $_FILES['goods_video']?$_FILES['goods_video']:"";
            if($upfile){
                $res = $this->upload_file($upfile);
                $data['goods_video'] = $res;
            }
        }
        $level_ids = $_POST['level_id'];
        $level_commission = $_POST['level_commission'];
        $level_set = array();
        foreach($level_ids as $k=>$v){
            $level_set[$k]['id'] = $v;
            $level_set[$k]['commission'] = $level_commission[$k];
        }
        $level_set_str = json_encode($level_set);
        $data['level_set'] = $level_set_str;

     
        // 更新记录
        if ($model->edit($data)) {
            return $this->renderSuccess('更新成功', url('goods/index'));
        }
        return $this->renderError($model->getError() ?: '更新失败');
    }

    function upload_file($files, $path = "./upload", $imagesExt = ['jpg', 'png', 'jpeg', 'gif', 'mp4'])
    {
        // 判断错误号
        if (@$files['error'] == 00) {
            // 判断文件类型
            $ext = strtolower(pathinfo(@$files['name'], PATHINFO_EXTENSION));
            if (!in_array($ext, $imagesExt)) {
                return "非法文件类型"; }

            // 判断是否存在上传到的目录
            if (!is_dir($path)) {
                mkdir($path, 0777, true);
            }

            // 生成唯一的文件名
            $fileName = md5(uniqid(microtime(true), true)) . '.' . $ext;

            // 将文件名拼接到指定的目录下
            $destName = "upload/" . $fileName;

            // 进行文件移动
            if (!move_uploaded_file($files['tmp_name'], $destName)) {
                return "文件上传失败！";
            }
            return $destName;
        }
        else {
            // 根据错误号返回提示信息
            switch (@$files['error']) {
                case 1:
                    echo "上传的文件超过了 php.ini 中 upload_max_filesize 选项限制的值";
                    break;
                case 2:
                    echo "上传文件的大小超过了 HTML 表单中 MAX_FILE_SIZE 选项指定的值";
                    break;
                case 3:
                    echo "文件只有部分被上传";
                    break;
                case 4:
                    echo "没有文件被上传";
                    break;
                case 6:
                case 7:
                    echo "系统错误";
                    break;
            }
        }
    }
    /**
     * 修改商品状态
     * @param $goods_id
     * @param boolean $state
     * @return array
     */
    public function state($goods_id, $state)
    {
        // 商品详情
        $model = GoodsModel::detail($goods_id);
        if (!$model->setStatus($state)) {
            return $this->renderError('操作失败');
        }
        return $this->renderSuccess('操作成功');
    }

    /**
     * 删除商品
     * @param $goods_id
     * @return array
     */
    public function delete($goods_id)
    {
        // 商品详情
        $model = GoodsModel::detail($goods_id);
        if (!$model->setDelete()) {
            return $this->renderError($model->getError() ?: '删除失败');
        }
        return $this->renderSuccess('删除成功');
    }

}
